
import { constantRouterMap } from '@/router'
import { sideMenuList } from '@/api/permission'
import Layout from '@/views/layout/Layout'
import auth from '@/plugins/auth'

export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    // console.log('route',route)
    if (route.perms) {
      if (auth.hasPermiOr(route.perms)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

// 动态路由遍历，验证是否具备权限
function filterDynamicRoutess(route) {
  if (route.perms) {
    if (auth.hasPermiOr([route.perms])) {
      return true
    } else {
      return false
    }
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param perms
 */
function filterAsyncRouter(routes) {
  const res = []
  // let routews = filterDynamicRoutes(routes)
  routes.forEach(route => {
    const tmp = { ...route }

    tmp.component = tmp.component ? loadView(tmp.component) : Layout

    if (tmp.children) {
      tmp.children = filterAsyncRouter(tmp.children)
      if (tmp.children && tmp.children.length > 0) {
        if (filterDynamicRoutess(tmp)) {
          res.push(tmp)
        }
      }
    } else {
      if (filterDynamicRoutess(tmp)) {
        res.push(tmp)
      }
    }
  })

  return res
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return sideMenuList().then(res => {
        const accessedRouters = filterAsyncRouter(res.data)
        accessedRouters.push({ path: '*', redirect: '/404', hidden: true })// 增加404兜底路由
        commit('SET_ROUTERS', accessedRouters)
      })
    }
  }
}

export default permission
